<template>
    <div>
     <el-row>
      <quillEditor
       ref="myQuillEditor"
       @change="onEditorChange($event)"
       v-model="value"
       :options="editorOption"/>
     </el-row>
    </div>
   </template>
   <script>
   import { quillEditor } from 'vue-quill-editor'//引用扩展
   import 'quill/dist/quill.core.css'
   import 'quill/dist/quill.snow.css'
   import 'quill/dist/quill.bubble.css'
   export default {
    name: "richText",
    components:{quillEditor},
    props:['content'],//父组件传过来的，将传过来的渲染到富文本编辑器
    data(){
     return{
      serverUrl:process.env.VUE_APP_BASE_API + '/upload', //上传的图片服务器地址
      uillUpdateImg:false,//根据图片上传状态来确定是否显示loading动画
      value:this.content,//富文本内容
      editorOption: {//符文本编辑器的配置
       placeholder: '',
       theme: 'snow',
       modules: {
        toolbar: {
         container: [// 工具栏配置, 默认是全部
          ['bold'],
          ['italic'],
          ['underline'],
          ['strike'],
          [{'list':'ordered'},{'list': 'bullet' }],
       //    ['blockquote'], ['code-block'],//不需要的可以干掉
          ['link'],
          ['image'],
          [{'list': 'ordered'}, {'list': 'bullet'}],
         ],
         handlers: {
          'image': function (value) {
           if (value) {
            // 给个点击触发Element-ui，input框选择图片文件
            document.querySelector('#quill-upload input').click()
           } else {
            this.quill.format('image', false);
           }
          }
         }
        }
       }
      }
     }
    },
    methods:{
     onEditorChange({ quill, html, text }) {   //富文本编辑器内容发生改变的时候
      this.value = html
      this.$emit('textChange',html)//将富文本编辑器输入的文本发送给父组件，父组件涉及提交添加或者更改
     },
     beforeUpload(){               //上传图片之前开启loading
      this.uillUpdateImg = true
     },
     uploadError(){               //图片上传失败,关闭loading
      this.uillUpdateImg = false
      this.$message.error('图片插入失败')
     },
     handleExceed(response, file, fileList){   //图片添加成功
      let quill = this.$refs.myQuillEditor.quill
      console.log(response)
      if (response.code === 0) {
       let length = quill.getSelection().index;
       // 插入图片 response.data.url为服务器返回的图片地址
       quill.insertEmbed(length, 'image', response.data.file_url)//image 是你请求接口传的key,
       // 调整光标到最后
       quill.setSelection(length + 1)
      }else{
       this.$message.error('图片插入失败')
      }
      this.fileList = fileList
      this.uillUpdateImg = false
     },
    }
   }
   </script>
   <style>
   .quillEditor{
      width: 50%;
      height: 700px;
   }
   </style>
   